class MyBlockingQueue{
    private String[] data = new String[100];
    private volatile int size ;
    private volatile int head = 0 ;
    private volatile int tail = 0 ;
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while (size == data.length){
                //队列满了唤醒;
                this.wait();
            }
            data[tail] = elem ;
            tail ++ ;
            size ++ ;
            if(tail == data.length){
                tail = 0 ;
            }
            this.notify() ;
        }
    }
    public String take() throws InterruptedException {
        synchronized (this) {
            if (size == 0) {
                this.wait();
            }
            String ret = data[head];
            head++;
            size--;
            if (head == data.length) {
                head = 0;
            }
            // 队列不满了, 唤醒 因为take而wait的线程
            this.notify();
            return ret;
        }
    }
}

public class Test3 {
    public static void main(String[] args) {
       // t1 代表生产者
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        Thread t1 = new Thread(()->{
           int num = 1 ;
           while (true){
               try {
                   myBlockingQueue.put(num+"");
                   System.out.println("生产元素:"+num);
                   num ++ ;
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        //t2 代表消费者
        Thread t2 = new Thread(()->{
            while (true){
                try {
                    String result = myBlockingQueue.take();
                    System.out.println("消费者消费:"+result);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();

    }


}
